import React from 'react';
import { Text, View, SafeAreaView, ScrollView, StyleSheet, TouchableOpacity, Image, Alert } from 'react-native';
import { connect } from 'react-redux';
import Tfa from '../component/tfa';

const styles = StyleSheet.create({
  container: {
    backgroundColor: 'rgba(0, 0, 0, 0.2)'
  },
  scan: {
    marginRight: 8
  },
  scanImg: {
    width: 28,
    height: 28
  },
  title: {
    fontSize: 20,
    marginLeft: 8
  },
  tipContainer: {
    backgroundColor: 'white',
    padding: 8,
  },
  tipText: {
    fontSize: 24,
  },
});

class HomeScreen extends React.PureComponent {
  static navigationOptions = ({navigation }) => {
    return {
      headerTitle: () => <Text style={styles.title} >MFA认证</Text>,
      headerRight: () => <TouchableOpacity style={styles.scan} onPress={() => navigation.navigate('Scanner')} ><Image source={require('../image/scan.png')}  style={styles.scanImg} resizeMode="cover" /></TouchableOpacity>
    };
  };

  componentDidMount() {
    const {dispatch} = this.props;
    dispatch({
      type: 'index/getTfa'
    });
  }

  onTfaRemove = (id) => {
    const {dispatch} = this.props;
    Alert.alert(
      '警告',
      '确定删除此条MFA吗？',
      [
        {
          text: '确定', onPress: () => {
            dispatch({
              type: 'index/removeTfa',
              payload: id,
            });
          }
        },
        {text: '取消'},
      ]
    )
  }

  getTfaView = () => {
    const tfaViews = this.props.tfa.map((item) => {
      return <Tfa key={item.id} onRemove={this.onTfaRemove} {...item} />
    });
    return tfaViews;
  }

  getTipView = () => {
    return (
      <View style={styles.tipContainer}>
        <Text style={styles.tipText}>请点击右上角<Image source={require('../image/scan.png')}  style={styles.scanImg} resizeMode="cover" />添加MFA认证</Text>
      </View>
    );
  };

  render() {
    return (
      <SafeAreaView>
        <ScrollView showsVerticalScrollIndicator={false} >
          <View style={styles.container}>
            {this.props.tfa.length > 0 ? this.getTfaView() : this.getTipView()}
          </View>
        </ScrollView>
      </SafeAreaView>
    );
  }
}

export default connect(({index}) => {
  return {tfa: index.tfa};
})(HomeScreen);
